package yja.gzw.app.activity

import android.Manifest
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Bundle
import android.os.CountDownTimer
import android.util.Log
import android.view.View
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.amap.api.location.AMapLocation
import com.amap.api.location.AMapLocationClient
import com.amap.api.location.AMapLocationClientOption
import com.amap.api.location.AMapLocationListener
import com.amap.api.maps.AMap
import com.amap.api.maps.CameraUpdateFactory
import com.amap.api.maps.MapView
import com.amap.api.maps.MapsInitializer
import com.amap.api.maps.model.LatLng
import com.amap.api.maps.model.MarkerOptions
import yja.gzw.app.R
import com.amap.api.services.core.AMapException
import com.amap.api.services.core.LatLonPoint
import com.amap.api.services.core.PoiItem
import com.amap.api.services.poisearch.PoiResult
import com.amap.api.services.poisearch.PoiSearch
import com.amap.api.services.poisearch.PoiSearch.OnPoiSearchListener
import com.amap.api.services.poisearch.PoiSearch.Query
import yja.gzw.app.adapter.DiminAdapter
import yja.gzw.app.adapter.FabuAdapter
import yja.gzw.app.adapter.TuijianAdapter
import yja.gzw.app.model.UserData


class MapsActivity : Activity(), AMapLocationListener, OnPoiSearchListener ,  DiminAdapter.OnItemClickListener{
    private var mapView: MapView? = null
    private var aMap: AMap? = null
    private lateinit var mLocationClient: AMapLocationClient
    private lateinit var mLocationOption: AMapLocationClientOption
    private var poiSearch: PoiSearch? = null
    var latitude:Double=34.709287
    var longitude:Double=113.627203
    var dw=false
    private lateinit var dimingada: DiminAdapter
    var listdiming=mutableListOf<String>()
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_maps)
        checkAndRequestPermission()



        MapsInitializer.updatePrivacyShow(this@MapsActivity, true, true)
        MapsInitializer.updatePrivacyAgree(this@MapsActivity, true)

        mapView = findViewById<View>(R.id.map) as MapView
        mapView?.onCreate(savedInstanceState) // 此方法必须重写
        init()
        initLocation()
        initPoiSearch()

        findViewById<TextView>(R.id.sousuo).setOnClickListener {
            var diming=findViewById<EditText>(R.id.sounei).text.toString()
            aMap?.clear()
            searchPoi(latitude,longitude,diming)



        }



    }
    fun  init(){
        if (aMap == null) {
            aMap = mapView!!.map
        }


    }
    private fun initPoiSearch() {
        poiSearch = PoiSearch(this, null)
        poiSearch?.setOnPoiSearchListener(this)
    }

    private fun checkAndRequestPermission() {
        // 首先检查权限是否已经被授予
        if (ContextCompat.checkSelfPermission(
                this,
                Manifest.permission.ACCESS_FINE_LOCATION
            ) != PackageManager.PERMISSION_GRANTED
        ) {
            // 如果没有授予权限，则发起权限请求
            ActivityCompat.requestPermissions(
                this,
                arrayOf(Manifest.permission.ACCESS_FINE_LOCATION),
                100
            )


        } else {



        }
    }


    private fun initLocation() {
        mLocationClient = AMapLocationClient(applicationContext)
        mLocationOption = AMapLocationClientOption()
        mLocationOption.locationMode = AMapLocationClientOption.AMapLocationMode.Hight_Accuracy
        mLocationOption.interval = 2000
        mLocationClient.setLocationOption(mLocationOption)
        mLocationClient.setLocationListener(this)
        mLocationClient.startLocation()
    }
    override fun onLocationChanged(location: AMapLocation?) {
        if (location != null) {
            if (location.errorCode == 0) {
                latitude = location.latitude
                longitude = location.longitude
                // 将定位结果显示在地图上
                val markerOption = MarkerOptions()
                markerOption.position(LatLng(latitude, longitude))
                markerOption.title("当前位置")
                Log.e("当前位置","x"+latitude+"   y"+longitude)
                aMap?.addMarker(markerOption)
                aMap?.moveCamera(CameraUpdateFactory.newLatLngZoom(LatLng(latitude, longitude), 15f))

                if(!dw){
                    searchPoi(latitude, longitude,"")

                }
                dw=true



            } else {
                // 定位失败时，可通过ErrCode（错误码）信息来确定失败的原因。
                Log.e("AmapError", "location Error, ErrCode:" + location.errorCode + ", errInfo:" + location.errorInfo)
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        mapView?.onDestroy();
    }

    override fun onResume() {
        super.onResume()
        mapView?.onResume();

    }

    override fun onPause() {
        super.onPause()
        mapView?.onPause();
    }

    override fun onPoiSearched(p0: PoiResult?, p1: Int) {
        if (p1 == AMapException.CODE_AMAP_SUCCESS) {
            if (p0 != null && p0.query != null) {
                if (p0.pois != null && p0.pois.size > 0) {
                    listdiming.clear()
                    for (item in p0.pois) {
                        val markerOption = MarkerOptions()
                        markerOption.position(LatLng(item.latLonPoint.latitude, item.latLonPoint.longitude))
                        markerOption.title(item.title)
                        Log.e("城市搜索", "Title: ${item.title}")

                        listdiming.add(item.title)

                        aMap?.addMarker(markerOption)
                    }


                  findViewById<RecyclerView>(R.id.diming).layoutManager=
                        LinearLayoutManager(this, LinearLayoutManager.VERTICAL,false)
                    dimingada= DiminAdapter(this,listdiming,this)
                    findViewById<RecyclerView>(R.id.diming).adapter= dimingada




                } else {
                    Log.e("PoiSearch", "No poi found")
                }
            } else {
                Log.e("PoiSearch", "No poi found")
            }
        } else {
            Log.e("PoiSearch", "Error code: $p1")
        }

    }

    override fun onPoiItemSearched(p0: PoiItem?, p1: Int) {

    }
    private fun searchPoi(latitude: Double, longitude: Double,diming:String) {
        val query = Query(diming, "", "")
        query.pageNum = 1
        query.pageSize = 20
        val startPoint = LatLonPoint(latitude, longitude)
        val poiSearch = PoiSearch(this, query) // 创建新的 PoiSearch 对象
        poiSearch.bound = PoiSearch.SearchBound(startPoint, 1000) // 设置查询范围
        poiSearch.setOnPoiSearchListener(this)
        poiSearch.searchPOIAsyn() // 执行搜索



     }

    override fun onItemClick2(position: Int, uri: String) {
       UserData.diming=uri
        finish()

    }

}